#include "tilesheet.hpp"

namespace sdl_engine {

TileSheet::TileSheet(const std::string& filename,
                     int row, int col,
                     const std::optional<Color>& keyColor)
    : row_(row), col_(col) {
    if (keyColor) {
        texture_ = std::make_unique<Texture>(filename, keyColor.value());
    } else {
        texture_ = std::make_unique<Texture>(filename);
    }
    if (!texture_) {
        row_ = 0;
        col_ = 0;
    }
}

SubTexture TileSheet::Get(int x, int y) {
    if (x >= 0 && x < col_ && y >= 0 && y < row_ ) {
        Size tileSize = size(texture_->GetSize().w / col_,
                             texture_->GetSize().h / row_);
        return SubTexture(
                   texture_.get(),
                   rect(x * tileSize.w, y * tileSize.h, tileSize.w, tileSize.h)
               );
    }

    return SubTexture(nullptr, rect(0, 0, 0, 0));
}

SubTexture TileSheet::Get(int idx) {
    int x = idx % col_,
        y = idx / col_;
    return Get(x, y);
}

}
